package com.carpedil.order.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/** @author Administrator */
@Configuration
public class OrderConfig {
  /**
   * restTemplate 交给spring 容器
   *
   * @return RestTemplate
   */
  @Bean
  public RestTemplate restTemplate() {
    return new RestTemplate();
  }

  /** 注入工厂（已经预加载） */
  @Resource CachingConnectionFactory connectionFactory;

  /** rabbitmq模板 */
  @Bean(value = "rabbitTemplate")
  public RabbitTemplate rabbitTemplate() {
    return new RabbitTemplate(connectionFactory);
  }

  /**
   * 创建一个死信队列
   *
   * @return deadQueue
   */
  @Bean
  public Queue deadQueue() {
    return new Queue("deadQueue");
  }
  /** 创建死信交换机 */
  @Bean
  public DirectExchange deadExchange() {
    return new DirectExchange("deadExchange");
  }
  /** 绑定死信交换机 */
  @Bean
  public Binding bindToDeadExchange(Queue deadQueue, DirectExchange deadExchange) {
    return BindingBuilder.bind(deadQueue).to(deadExchange).with("dead_routing_key");
  }

  /**
   * 创建一个队列 绑定死信队列
   *
   * @return Queue
   */
  @Bean
  public Queue queueOne() {
    Map<String, Object> args = new HashMap<>(3);
    // x-dead-letter-exchange    这里声明当前队列绑定的死信交换机
    args.put("x-dead-letter-exchange", "deadExchange");
    // x-dead-letter-routing-key  这里声明当前队列的死信路由key
    args.put("x-dead-letter-routing-key", "dead_routing_key");
    // x-message-ttl  声明队列的TTL(超时时间[毫秒])
    args.put("x-message-ttl", 20000);
    return QueueBuilder.durable("OrderQueue").withArguments(args).build();
  }

  /***
   * 创建一个普通交换机
   * @return DirectExchange
   */
  @Bean
  public DirectExchange directExchange() {
    return new DirectExchange("orderExchange");
  }

  @Bean
  public Binding bindingQueueWithDirectExchange(Queue queueOne, DirectExchange directExchange) {
    return BindingBuilder.bind(queueOne).to(directExchange).with("j178.order");
  }
}
